import React, { useState } from 'react';
import { Button, Form, Input, message, Modal, Select, Upload } from 'antd';
import moment from 'moment';

import { PLoading, TRCheckboxModal, TRMessage } from '#/components/index.js';
import { DownloadOutlined } from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';
import TRNotification from '#/utils/notification.js';

import type { ISearchFormData } from '../../type';
import { editAttachmentCustomH, upLoadFiles } from '../../service';
import { TRADE_TYPE_MODE_OPTIONS } from '../../dictionary';
import { DateAndTimePicker, ShowDatePicker, ShowSelect } from '../index';
import styles from './index.less';

const TextArea = Input.TextArea;
interface IProps {
  /**
   * 是否是编辑状态
   */
  isEdit: boolean;
  /**
   * searchFormData
   */
  searchFormData: ISearchFormData;
  /**
   * 刷新key值
   */
  setFlashKey: (e: number | string) => void;
  setMonthflashKey: (e: number) => void;
  onPress: (data: Record<string, any>) => void;
  /**
   * 序列详情
   */
  value?: any;
}

const SequenceModalComponent = (props: IProps) => {
  const {
    isEdit = false,
    searchFormData,
    value: _value,
    onPress,
    setFlashKey,
    setMonthflashKey,
  } = props;
  const [visible, setVisible] = useState<boolean>(true);
  const [attachmentsData, setattachmentsData] = useState<
    { attachmentName: string; attachmentPath: string }[]
  >([]);
  const [fileData, setFileData] = useState<{ uid: string; name: string }[]>([]);
  const [value, setValue] = useState<any>({});
  const [isLoading, setIsLoading] = useState<boolean>(false);

  const [form] = Form.useForm();

  const { dealElementOptions, dealElementModalOptions, dealElementDataObj, marketOptions } =
    searchFormData;

  React.useEffect(() => {
    if (_value) {
      const data = {
        ..._value,
        tradeSequenceName: _value?.title || '',
        stationList: _value?.stationIds ? _value?.stationIds?.split(',') : [],
        executionDate:
          _value?.executionStartDate && _value?.executionEndDate
            ? [moment(_value?.executionStartDate), moment(_value?.executionEndDate)]
            : [],
        declarationTime:
          _value?.declarationStartTime && _value?.declarationEndTime
            ? {
                declarationStartTime: _value?.declarationStartTime,
                declarationEndTime: _value?.declarationEndTime,
              }
            : {},
      };
      form && form.setFieldsValue(data);
      setValue(data);
      setattachmentsData(
        _value?.attachmentIds && _value?.attachmentNames
          ? _value?.attachmentIds?.split(',').map((item: string, index: number) => {
              return {
                attachmentPath: item,
                attachmentName: _value?.attachmentNames?.split(',')[index],
              };
            })
          : [],
      );
      setFileData(
        _value?.attachmentIds && _value?.attachmentNames
          ? _value?.attachmentIds?.split(',').map((item: string, index: number) => {
              return { uid: item, name: _value?.attachmentNames?.split(',')[index] };
            })
          : [],
      );
    }
  }, [_value]);

  //  取消按钮
  const _onCancel = () => {
    setVisible(false);
    onPress({ index: 0 });
  };

  // 点击交易单元弹出Modal框
  const handelSelectDealElement = async () => {
    let data = form.getFieldsValue()?.stationList || [];
    data = data.map((item: any) => dealElementDataObj[item]?.[0]?.value);
    const result = await TRCheckboxModal.show({
      treeData: dealElementModalOptions,
      value: data,
      title: '交易单元',
    });
    if (result.index === 1) {
      const checkedKeys = result?.checkedKeys?.map(
        (item: any) => dealElementDataObj?.[item]?.[0]?.value,
      );
      form.setFieldsValue({ stationList: checkedKeys });
    }
  };

  // 表单提交
  const onSubmit = () => {
    form &&
      form.validateFields().then(async (values) => {
        setIsLoading(true);
        const {
          executionDate = [],
          declarationTime = {},
          id = '',
          stationList = [],
          marketId = '',
          ...rest
        } = { ...value, ...values };

        let res: any = {};
        const executionStartDate = moment(executionDate[0]).format('YYYY-MM-DD');
        const executionEndDate = moment(executionDate[1]).format('YYYY-MM-DD');
        const declarationStartTime = declarationTime?.declarationStartTime
          ? moment(declarationTime?.declarationStartTime).format('YYYY-MM-DD HH:mm:ss')
          : null;
        const declarationEndTime = declarationTime?.declarationEndTime
          ? moment(declarationTime?.declarationEndTime).format('YYYY-MM-DD HH:mm:ss')
          : null;
        const hljParams = {
          ...rest,
          tradeSequenceId: id || null,
          marketId,
          stationIds: stationList.join(','),
          stationNames: stationList
            .map((item: any) => dealElementDataObj[item]?.[0]?.label)
            .join(','),
          marketName: marketOptions.find((item) => item.value === marketId)?.label || '',
          attachmentIds: attachmentsData.map((item: any) => item.attachmentPath)?.join(','),
          attachmentNames: attachmentsData.map((item: any) => item.attachmentName)?.join(','),
          executionStartDate,
          executionEndDate,
          declarationStartTime,
          declarationEndTime,
        };

        if (isEdit) {
          res = await editAttachmentCustomH({
            update: [hljParams],
          });
        } else {
          res = await editAttachmentCustomH({
            add: [hljParams],
          });
        }
        if (res && res.statusCode === HttpCode.SUCCESS) {
          if (isEdit) {
            setFlashKey(`${moment().valueOf()}edit`);
          } else {
            setFlashKey(moment().valueOf());
          }
          setMonthflashKey(moment().valueOf());
          message.info('保存成功！');
          setVisible(false);
          onPress({ index: 1, newId: isEdit ? res.data : '', oldId: id });
        } else {
          message.info(res?.message || '保存失败！');
        }
        setIsLoading(false);
      });
  };

  const customRequest = async ({ file }: any) => {
    const errorList = [];
    const attachments = [...attachmentsData];
    const useFileName = file?.name.split('.')[0];
    const useFileType = file?.name.split('.')[1];
    let newfileName = file.name;
    let sum = 0;
    attachments.forEach((item) => {
      if (item?.attachmentName?.includes(useFileName)) {
        sum += 1;
      }
    });
    if (sum > 0) {
      newfileName = `${useFileName}(${sum}).${useFileType}`;
    }
    const fileList = [...fileData, { ...file, name: newfileName }];
    if (file.status !== 'uploading' && file.status !== 'removed') {
      PLoading.show('上传附件中...');
      const pdata = new window.FormData();
      pdata.append('file', file);
      pdata.append('fileName', newfileName);
      const res = await upLoadFiles(pdata);
      PLoading.dismiss();
      if (res && res?.statusCode === HttpCode.SUCCESS) {
        attachments.push({ attachmentPath: res?.uploadBody?.fileId, attachmentName: newfileName });
        TRMessage.success('上传成功');
      } else {
        fileList[fileList?.length - 1].status = 'error';
        fileList[fileList?.length - 1].response = res?.message || '上传失败';
        errorList.push(res?.message || '上传失败');
      }
    }
    setFileData(fileList);
    setattachmentsData(attachments);
  };

  const filterOption = (input: string, option: { value: any; label: any }) => {
    return (
      option?.value?.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
      option?.label?.toLowerCase().indexOf(input.toLowerCase()) >= 0
    );
  };

  const handleChange = ({ file, fileList }: any) => {
    if (file.status === 'removed') {
      const attachments = attachmentsData.filter(
        (z: any) => fileList.filter((y: any) => y.name === z.attachmentName)?.length > 0,
      );
      setFileData(fileList);
      setattachmentsData(attachments);
    }
  };

  const footerRender = () => [
    <Button key="dtest1" onClick={_onCancel} loading={isLoading}>
      取消
    </Button>,
    <Button key="dtest2" type="primary" onClick={onSubmit} loading={isLoading}>
      提交
    </Button>,
  ];

  return (
    <Modal
      width="60%"
      className={styles.modal}
      centered
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <span className={styles.title}>{isEdit ? '编辑交易序列' : '新建交易序列'}</span>
        </div>
      }
      onCancel={_onCancel}
      footer={footerRender()}
    >
      <div className={styles.container}>
        <Form
          className={styles.form}
          form={form}
          name="sequence"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          colon={false}
          labelAlign="left"
          autoComplete="off"
          requiredMark={false}
        >
          <Form.Item
            name="tradeSequenceName"
            label="序列名称"
            rules={[
              { required: true, message: '请填写序列名称' },
              { max: 50, message: '序列名称不可超过50个字符' },
            ]}
          >
            <TextArea maxLength={50} placeholder="请填写序列名称" />
          </Form.Item>
          <Form.Item
            name="marketId"
            label="发布单位"
            rules={[{ required: true, message: '请选择发布单位' }]}
          >
            <ShowSelect
              placeholder={'发布单位'}
              showArrow={true}
              options={marketOptions}
              showSearch={true}
              filterOption={filterOption as any}
            />
          </Form.Item>
          <Form.Item name="tradeTypeMode" label="交易方式">
            <ShowSelect
              options={TRADE_TYPE_MODE_OPTIONS}
              placeholder={'交易方式'}
              showArrow={true}
              allowClear
            />
          </Form.Item>
          <Form.Item
            label="交易申报时间"
            name="declarationTime"
            rules={[{ required: true, message: '请选择交易申报时间' }]}
          >
            <DateAndTimePicker />
          </Form.Item>
          <Form.Item
            name="executionDate"
            label="交易执行时间"
            rules={[{ required: true, message: '请选择交易执行时间' }]}
          >
            <ShowDatePicker
              type="rangePicker"
              format="YYYYMMDD"
              placeholder={['开始时间', '结束时间']}
            />
          </Form.Item>
          <Form.Item label="附件">
            <Upload
              customRequest={customRequest}
              onChange={handleChange}
              fileList={fileData}
              accept=".pdf,.doc,.docx,.xls"
            >
              <DownloadOutlined style={{ color: 'var(--font-primary)', marginRight: '8px' }} />
              <a>导入</a>
            </Upload>
          </Form.Item>
          <Form.Item
            name="stationList"
            label="相关单元"
            rules={[{ required: true, message: '请选择相关单元' }]}
          >
            <Select
              placeholder={'相关单元'}
              showArrow={true}
              open={false}
              onClick={handelSelectDealElement}
              mode="multiple"
              maxTagTextLength={1}
              maxTagCount={1}
              options={dealElementOptions as any[]}
            />
          </Form.Item>
        </Form>
      </div>
    </Modal>
  );
};

class SequenceModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <SequenceModalComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new SequenceModal();
